const axios = require('axios');
import qs from 'qs';
import config from '../common/config.js';
export default {
    install: function(Vue, options) {
        let token = localStorage.getItem('token');
        let version = localStorage.getItem('version');
        let read_mode = localStorage.getItem('read_mode');
        let userid = localStorage.getItem('userid');

        let authorization = '';
        Vue.prototype.$axios = axios;
        let time_zone = new Date().getTimezoneOffset() / 60
        let params = {
            "_token": token,
            "time_zone": time_zone.toString().replace(/\+/g, '%2B'),
            "display": 'web',
        }

        version && (params.version = version);
        userid && (params.userid = userid);
        read_mode && (params.read_mode = read_mode);


        Vue.prototype.$http = axios.create({
            baseURL: config.api,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
            },
            params,
            transformRequest: [function(data, headers) {
                return qs.stringify(data);
            }]
        });

        Vue.prototype.$http.interceptors.response.use(function(response) {
            if (response.data.code === 4001) {
                localStorage.removeItem('member_info')
                localStorage.removeItem('token')
                if (location.pathname.indexOf('my_center.html') !== -1) {
                    return response;
                } else {
                    location.href = config.pages.login;
                    return Promise.reject(new Error('未登录'));
                }
            } else {
                return response;
            }
        }, function(error) {
            // Do something with response error
            return Promise.reject(error);
        });
    }
}